package com.masasdani.appstore.controller;

import com.alibaba.fastjson2.JSONObject;
import com.masasdani.paypal.domain.Orders;
import com.masasdani.paypal.service.PayPalSubscriptionService;
import com.masasdani.paypal.service.PaypalService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * paypal支付控制类
 */
@Controller
@RequestMapping("/appstore/")
public class AppStoreController {

	private static final String PRODUCTION_URL = "https://buy.itunes.apple.com/verifyReceipt";
	private static final String SANDBOX_URL = "https://sandbox.itunes.apple.com/verifyReceipt";

	public static final String PAYPAL_REFUND_URL = "refund/success";

	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PaypalService paypalService;

	@Autowired
	private PayPalSubscriptionService payPalSubscriptionService;


	/**
	 * 创建AppStore订单
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.POST, value = "createOrders")
	public static Orders createOrder(Orders orders)  {
		boolean sandbox = true;
		//生成订单
//		orders.setOrderTime(DateUtils.getNowDate());
//		orders.setOrderNumber(OrderUtils.getOrderCode(Integer.parseInt(String.valueOf(userId))));
//		orders.setQuantity(SysConstantUtils.INT_1);
//		orders.setUserId(userId);
//		orders.setDueTime(DateUtils.getDateByNowDateAndMonth(DateUtils.getNowDate(),goods.getIncreaseMonth()));
//		orders.setAmount(goods.getPrice());
//		orders.setCurrency(goods.getCurrency());
//		orders.setPayMethod(SysConstantUtils.INT_1);
//		orders.setCreateTime(DateUtils.getNowDate());
//		orders.setStatus(SysConstantUtils.INT_0);
//		orders.setPaymentId(payment.getId());
//		ordersService.insertOrders(orders);

		return orders;
	}


	/**
	 * AppStore支付成功后验证
	 * @param receiptData
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(method = RequestMethod.GET, value = "validateReceipt")
	public static Boolean validateReceipt(String receiptData) throws IOException {
		boolean sandbox = true;
		String url = sandbox ? SANDBOX_URL : PRODUCTION_URL;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setEntity(new StringEntity("{\"receipt-data\":\"" + receiptData + "\"}"));

		try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
			String result = EntityUtils.toString(response.getEntity());
			JSONObject resultJson = JSONObject.parseObject(result);
			// 检查是否有效
			if (resultJson.getIntValue("status") == 0) {
				System.out.println("Receipt is valid.");

				//TODO 支付成功更新订单

				//TODO 支付成功更新用户时长
				return true;
			}
			return false;
		}
	}

	/**
	 * 支付退款
	 * @param orderId
	 * @param refundRequest
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_REFUND_URL)
	public Map<String, Object> processRefund(@RequestParam("orderId") String orderId, @RequestBody Map<String, Object> refundRequest) {
		String reason = (String) refundRequest.get("reason");

		// 假设这里处理退款并将结果存入数据库
		Map<String, Object> response = new HashMap<>();
		response.put("orderId", orderId);
		response.put("status", "REFUNDED");
		response.put("reason", reason);

		//TODO 退款成功更新订单

		//TODO 退款成功更新用户时长

		return response;
	}

}
